package app.project.streetlensproject.map;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import app.project.streetlensproject.R;
import app.project.streetlensproject.fragment.FgCategory;
import app.project.streetlensproject.model.Category;
import app.project.streetlensproject.model.Place;
import app.project.streetlensproject.serverapi.ServerAPI;
import app.project.streetlensproject.util.AsyncTask;
import app.project.streetlensproject.util.CommonUtils;
import app.project.streetlensproject.util.Constants;
import app.project.streetlensproject.util.EmailValidator;
import app.project.streetlensproject.util.GPSTracker;
import app.project.streetlensproject.util.GetDataTask;
import app.project.streetlensproject.util.IGetDataTask;
import app.project.streetlensproject.util.Utilities;

public class PlaceEditActivity extends Activity {

	private GoogleMap map;
	public static final LatLng HANOI = new LatLng(20.993776, 105.811417);
	private static int RESULT_LOAD_IMAGE = 1;
	Place place;
	LatLng placeClick;
	MarkerOptions mkOption1;
	public String pathImage = "";
	private TextView mTextViewUser;

	@Override
	public void onCreate(Bundle circle) {
		super.onCreate(circle);
		setContentView(R.layout.activity_place_edit);

		createViewInit();
	}

	/**
	 * create view initial
	 */
	private void createViewInit() {

		String nameUser = CommonUtils.getStringSetting(PlaceEditActivity.this,
				Constants.USER_NAME, "Guest");
		mTextViewUser = (TextView) findViewById(R.id.textViewUserName);
		mTextViewUser.setText(getResources().getString(R.string.name_hello) + nameUser);

		GPSTracker gps;
		gps = new GPSTracker(PlaceEditActivity.this);
		LatLng myLocation = null;
		// check if GPS enabled
		if (gps.canGetLocation()) {
			double latitude = gps.getLatitude();
			double longitude = gps.getLongitude();
			myLocation = new LatLng(latitude, longitude);
		}

		MarkerOptions mkOption = new MarkerOptions()
				.position(myLocation)
				.title("My location !")
				.snippet("@@@")
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.icn_mylocation));

		map = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.mapPlaceEdit)).getMap();

		// add maker to map
		map.addMarker(mkOption);

		place = (Place) getIntent().getSerializableExtra("place");
		placeClick = new LatLng(place.locationx, place.locationy);
		mkOption1 = new MarkerOptions()
				.position(placeClick)
				.title(place.placename)
				.snippet(place.description)
				.icon(Utilities.getInstance().getBitmapDescriptionFromType(
						place.categoryid));

		map.addMarker(mkOption1);

		final Dialog dl = new Dialog(PlaceEditActivity.this);
		dl.requestWindowFeature(Window.FEATURE_NO_TITLE);
		View v = createViewDialogEditPlace(PlaceEditActivity.this, place, dl);
		dl.setContentView(v);
		dl.show();

		// Move the camera instantly to hamburg with a zoom of 20.
		map.moveCamera(CameraUpdateFactory.newLatLngZoom(placeClick, 20));

		// Zoom in, animating the camera.
		map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);

		map.setOnMarkerClickListener(onMarkerClickListener);
	}

	OnMarkerClickListener onMarkerClickListener = new OnMarkerClickListener() {

		public boolean onMarkerClick(Marker marker) {
			// TODO Auto-generated method stub
			// DialogUtils.getInstance().showDialogEdit(PlaceEditActivity.this);
			final Dialog dl = new Dialog(PlaceEditActivity.this);
			dl.requestWindowFeature(Window.FEATURE_NO_TITLE);
			View v = createViewDialogEditPlace(PlaceEditActivity.this, place,
					dl);
			dl.setContentView(v);
			dl.show();
			return false;
		}
	};

	ImageView imageViewAddImage;

	/**
	 * create view dialog edit
	 * 
	 * @param context
	 * @return
	 */
	public View createViewDialogEditPlace(final Context context,
			final Place placeEdit, final Dialog dl) {

		String description = placeEdit.description;

		LayoutInflater mLayoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View view = mLayoutInflater.inflate(R.layout.dialog_maker_edit, null);
		final EditText editTextName = (EditText) view
				.findViewById(R.id.editTextPlaceName);
		final Spinner spinnerCategory = (Spinner) view
				.findViewById(R.id.spinnerPlaceCategory);
		final EditText editTextAddress = (EditText) view
				.findViewById(R.id.editTextPlaceAddress);
		final EditText editTextMobile = (EditText) view
				.findViewById(R.id.editTextPlaceMobile);
		final EditText editTextMobilePhone = (EditText) view
				.findViewById(R.id.editTextPlaceMobilePhone);
		final EditText editTextFax = (EditText) view
				.findViewById(R.id.editTextPlaceFax);
		final EditText editTextVideo = (EditText) view
				.findViewById(R.id.editTextPlaceVideo);
		final EditText editTextWebsite = (EditText) view
				.findViewById(R.id.editTextPlaceWebsite);
		final EditText editTextEmail = (EditText) view
				.findViewById(R.id.editTextPlaceEmail);
		final EditText editTextInfor = (EditText) view
				.findViewById(R.id.editTextPlaceInfor);

		imageViewAddImage = (ImageView) view
				.findViewById(R.id.imageViewPlaceAddImage);
		Button buttonAdd = (Button) view.findViewById(R.id.buttonPlaceAdd);
		buttonAdd.setText("Edit place");
		editTextName.setText(placeEdit.placename);
		editTextInfor.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_INFO, description));
		editTextAddress.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_ADDRESS, description));
		editTextMobile.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_MOBILE, description));
		editTextMobilePhone.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_MOBILE_PHONE, description));
		editTextFax.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_FAX, description));
		editTextVideo.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_VIDEO, description));
		editTextWebsite.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_WEBSITE, description));
		editTextEmail.setText(Utilities.getInstance().getValueByType(
				Constants.TYPE_EMAIL, description));

		// String[] arrCategory = context.getResources().getStringArray(
		// R.array.arrCategory);

		ArrayList<Category> arrCategory = FgCategory.items;
		ArrayList<String> arrList = new ArrayList<String>();
		for (int i = 0; i < arrCategory.size(); i++) {
			arrList.add(arrCategory.get(i).name);
		}

		ArrayList<String> valuesCategory=new ArrayList<String>();
		// check is vietnamese or english..default is english
		boolean isEn = CommonUtils.getBooleanSetting(this, Constants.IS_EN, false);
		if(isEn){
			valuesCategory = Utilities.getInstance()
					.getValueCategory(arrList, Constants.LANGUAGE_EN);
		}else{
			valuesCategory = Utilities.getInstance()
					.getValueCategory(arrList, Constants.LANGUAGE_VN);
		}
		
		ArrayAdapter<String> adp = new ArrayAdapter<String>(context,
				android.R.layout.simple_spinner_item, android.R.id.text1,
				valuesCategory);

		spinnerCategory.setAdapter(adp);

		imageViewAddImage.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// go to gallery folder and add to
				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});

		buttonAdd.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (!Utilities.getInstance().checkInputFormat(
						editTextName.getText().toString())
						|| !Utilities.getInstance().checkInputFormat(
								editTextInfor.getText().toString())) {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.message_alert_input_blank),
							Toast.LENGTH_LONG).show();
				} else if (new EmailValidator().validate(editTextEmail
						.getText().toString())) {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.message_email_error),
							Toast.LENGTH_LONG).show();
				} else {
					// operation edit place
					// execute api to edit place
					float latitude = Float.parseFloat(String
							.valueOf(placeEdit.locationx));
					float longitude = Float.parseFloat(String
							.valueOf(placeEdit.locationy));
					String nameEdit = editTextName.getText().toString()
							.replace("*", "");
					String addressEdit = editTextAddress.getText().toString()
							.replace("*", "");
					String mobileEdit = editTextMobile.getText().toString()
							.replace("*", "");
					String mobilePhoneEdit = editTextMobilePhone.getText()
							.toString().replace("*", "");
					String faxEdit = editTextFax.getText().toString()
							.replace("*", "");
					String videoEdit = editTextVideo.getText().toString()
							.replace("*", "");
					String websiteEdit = editTextWebsite.getText().toString()
							.replace("*", "");
					String emailEdit = editTextEmail.getText().toString()
							.replace("*", "");
					String inforEdit = editTextInfor.getText().toString()
							.replace("*", "");
					int categoryID = spinnerCategory.getSelectedItemPosition();
					String time = DateFormat.format("MM,dd,yyyy ",
							new Date().getTime()).toString();
					String imageString = "";
					if (!pathImage.equals("")) {
						try {
							imageString = Utilities.getInstance()
									.getStringBase64FromImage(pathImage);
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							imageString = "";
							e.printStackTrace();
						}
					}

					String descriptionEdit = Utilities.getInstance()
							.getDescriptionValue(inforEdit, addressEdit,
									mobileEdit, mobilePhoneEdit, faxEdit,
									videoEdit, websiteEdit, emailEdit);

					Place placeEdited = new Place(latitude, longitude,
							nameEdit, descriptionEdit, categoryID,
							placeEdit.uniqueid, imageString, time, time);
					editPlaceToServer(placeEdited, dl);
					dl.dismiss();
				}

			}
		});

		return view;
	}

	/**
	 * @param place
	 */
	private void editPlaceToServer(final Place place, final Dialog dialog) {
		new GetDataTask(PlaceEditActivity.this, new IGetDataTask() {

			@Override
			public boolean doInBackGround() throws Exception {
				boolean resultFlag = ServerAPI.EditUserPlaces(CommonUtils
						.getStringSetting(PlaceEditActivity.this,
								Constants.TOKEN_ID, null), place.uniqueid,
						place.locationx, place.locationy, place.placename,
						place.description, place.image, place.categoryid);
				return resultFlag;
			}

			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);

				String tokenID = CommonUtils.getStringSetting(
						PlaceEditActivity.this, Constants.TOKEN_ID, "");
				Log.e("TokenID", tokenID);

				if (result) {
					Toast.makeText(getBaseContext(), "Edit place success",
							Toast.LENGTH_LONG).show();
					dialog.dismiss();
				}
			}

		}, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			pathImage = picturePath;
			cursor.close();
			imageViewAddImage.setImageBitmap(BitmapFactory
					.decodeFile(picturePath));
		}
	}
}